package com.excel.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.utils.JsonResult;

/**
 * @Title: UploadDownloadService.java
 * @Package com.excel.service
 * @author 孙梦楠
 * @date 2017年11月4日 下午4:11:13
 * @version V1.0.0
 */
@Service
public class UploadDownloadService {

	public String upload(MultipartFile file) throws IllegalStateException, IOException {

		if (file.isEmpty()) {
			return null;
		}
		SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String fileName = smf.format(new Date())+ "-"+file.getOriginalFilename();
		String path = "d:/temp";
		File dest = new File(path + "/" + fileName);
		if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
			dest.getParentFile().mkdir();
		}
		
			file.transferTo(dest); // 保存文件
			return path + "/" + fileName;
		

	}
	
	@Transactional
	public JsonResult<String> downLoad(HttpServletResponse res,String filename) {
		String filePath = "d:/temp";
		File file = new File(filePath + "/" + filename);
//		res.setHeader("content-type", "application/octet-stream");
//		res.setContentType("application/octet-stream");
//		res.setHeader("Content-Disposition", "attachment;filename=" + filename);
		res.setHeader("conent-type", "application/octet-stream");  
		res.setContentType("application/octet-stream");  
		try {
			res.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(file));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("success");
		file.delete();

		return new JsonResult<String>(0, null, null);
	}

}
